package org.twndmv.blimpl;

import java.io.InputStream;

import javax.persistence.EntityManager;
import javax.xml.bind.JAXBException;
import javax.xml.stream.XMLStreamException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twndmv.bl.DmvIngestor;
import org.twndmv.bl.DmvTestUtil;
import org.twndmv.dao.PersonDAO;
import org.twndmv.dao.VehicleRegistrationDAO;
import org.twndmv.jpa.DBUtil;

public class DmvTestUtilImpl implements DmvTestUtil {

	private static Log log = LogFactory.getLog(DmvTestUtilImpl.class);
	
	    protected static final String DROP_SCRIPT =
	        "ddl/twndmvDrop.ddl";
	    protected static final String CREATE_SCRIPT =
	        "ddl/twndmvCreate.ddl";
	    protected static final String POPULATE_SCRIPT =
		        "ddl/twndmvPopulate.ddl";
	    protected EntityManager em;

	    public void setEntityManager(EntityManager em) {
	        this.em = em;
	    }
	    
	    protected DBUtil getDBUtil() {
	        DBUtil dbUtil = new DBUtil();
	        dbUtil.setEntityManager(em);
	        dbUtil.setDropPath(DROP_SCRIPT);
	        dbUtil.setCreatePath(CREATE_SCRIPT);
	        return dbUtil;
	    }
	
	public void resetAll() {
		DBUtil dbUtil = getDBUtil();
		try {
			dbUtil.dropAll();
			dbUtil.createAll();
		} catch (Exception e) {
			log.error("Unable to reset DB in DMV Test Util: ", e);
		}
		
	}

	public void populate(PersonDAO personDB, VehicleRegistrationDAO vehicleDB, InputStream is) throws JAXBException, XMLStreamException, Exception {
		DmvIngestor ingestor = new DmvIngestorImpl();
		ingestor.setPersonDAO(personDB);
		ingestor.setInputStream(is);
		ingestor.setVehicleDAO(vehicleDB);
		ingestor.ingest();
	}

}
